package com.attilax.movcms;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

//import org.apache.commons.collections4.map.ListOrderedMap;























import com.attilax.core;
import com.attilax.atian.PinyinX;
import com.attilax.exception.ExUtil;
import com.attilax.formatter.FormatterEasyuiImp;
import com.attilax.index.IndexManager;
import com.attilax.index.IndexStoreService;
import com.attilax.io.dirx;
import com.attilax.io.filex;
import com.attilax.io.pathx;
import com.attilax.json.AtiJson;
import com.attilax.lang.Closure;
import com.attilax.lang.Closure2;
import com.attilax.lang.ParamX;
import com.attilax.lang.SerialUtil;
import com.attilax.lang.YamlAtiX;
import com.attilax.text.strUtil;
import com.attilax.util.PropX;
import com.attilax.util.numUtil;
import com.attilax.util.timeTester;

/**
 * { 'application_type': null, 'update_user': null, 'detail': '',
 * 'can_down_org': '', 'file_path': '动作类\\三日刺杀\\三日刺杀.mkv', 'material_type': 3,
 * 'effectie_time': null, 'txt_file': 'uploadfiles/动作类/三日刺杀/三日刺杀.txt',
 * 'material_keyword': 'srcs', 'material_id': 8604, 'director': null,
 * 'logicDel': null, 'size': '', 'material_description': '三日刺杀', 'staring':
 * null, 'update_time': null, 'play_time': 0, 'special_id': null, 'create_time':
 * null, 'create_user': null, 'thumb': 'images/p4.jpg', 'failure_time': null }
 * 
 * @author Administrator
 *
 */
// aaaCms.CmsImpLocalFileVer.list
//aaaCms.CmsImpLocalFileVer.list_ori
@SuppressWarnings("all")
public class CmsImpLocalFileVer {

	public static String maindir = "z:/";

	public static void main(String[] args) {
		//ListOrderedMap a
	//	maindir="d:/z/";
		// Object list = new CmsImpLocalFileVer().list("param=1");
	 //	Object list = new CmsImpLocalFileVer().search("param=1");
	//	Object list = new CmsImpLocalFileVer().searchV2("gzy");
		Object list=new CmsImpLocalFileVer().get_post_api("动作类/V字仇杀队/V字仇杀队.mkv");
		System.out.println(list);
		// System.out.println(new
		// CmsImpLocalFileVer().getCateid("d:/z/爱情类/100次哭泣/100次哭泣.jpg")); ;

		// new CmsImpLocalFileVer().getFileName("Z:\\动作类\\V字仇杀队");
	}
	
	
	public Object	get_post_intro(Object txt_url)
	{
		try {
			txt_url=URLDecoder.decode(  txt_url.toString(), "utf8");
		} catch (UnsupportedEncodingException e) {
			ExUtil.throwExV2(e);
		}
		String t=filex.read("z:/"+txt_url, "gbk");
		return t;
		
		
	}
	public Object	get_posts(Object paramsMap)
	{
		return paramsMap;
		
	}
	
	/**
	 * id zeush mkv path
	 * @param id
	 * @return
	 */
	public Object	get_post(Object id)
	{
		
				Map mv=new HashMap();
				String resDir =(String) id;
				resDir="z:/"+resDir;
				resDir=new File(resDir).getParent();
				mv.put("file_path", getFileName(resDir));
				mv.put("thumb", getPicName(resDir));
				mv.put("txt_file", getTxtName(resDir));
				String mov_name=new File((String) id).getParentFile().getName();
				mv.put("material_description", mov_name);

				 
		return mv;
		
	}
	//"file_path":"动作类\\V字仇杀队/V字仇杀队.mkv",
	public Object	get_post_api(Object id)
	{
		
		String mv="";
		if(numUtil.isNum(id))
		{
			String f=pathx.classPathParent_jensyegeor()+"/index_movs.txt";
			PropX px=new PropX(f,"gbk");
			mv=px.getProperty((String) id);
			if(id==null)
				throw new RuntimeException("ex:cant_find_mv:f:"+f+" ,id:"+id+" ,mv:"+mv);
			 
		}else
		{
			try {
				mv=URLDecoder.decode(  id.toString(), "utf8");
			} catch (UnsupportedEncodingException e) {
				ExUtil.throwExV2(e);
			}
		}
		Map m=(Map) get_post(mv);
		List<Map> movs=new ArrayList<Map>();
		movs.add(m);
		return AtiJson.toJson(FormatterEasyuiImp.fmtList(movs));
		
		
	}
	/**
	 * with cache
	 * @param obj
	 * @return
	 */
	public Object list(Object obj) {

		Map m = new ParamX().urlParams2Map(obj.toString());
		String cate_id = (String) m.get("param");

		List<Map> movs = list_cache(cate_id);
		 
		System.out.println("--get movs size:" + movs.size());
		return core.toJsonStrO88(FormatterEasyuiImp.fmtList(movs));
	}; 
	public Object list_nocache(String cate_id) {
	//	=params;
		List<Map> movs = list_ori(cate_id);
		System.out.println("--get movs size:" + movs.size());
		
		String jsonStrO88 = AtiJson.toJson(FormatterEasyuiImp.fmtList(movs));
		filex.saveLog(jsonStrO88, "C:\\jsonx");
		return jsonStrO88;
	}
	
	public String getCateid(String f) {
		String f_relate =f;
		if(f.contains(":"))  //thumb format
		{
			int startIdx = maindir.length();
			
			try {
				f_relate=f.substring(startIdx);
			} catch (Exception e) {
				System.out.println("");
			}
		}
		String[] a = f_relate.split("/");
		String cate = a[0].trim();
		// a[1 + new CmsImpLocalFileVer().getOffsetlen()];
		String s = pathx.classPathParent_jensyegeor() + "/cate.txt";
		Map m = YamlAtiX.getMapReverse(s);
		String cateid = (String) m.get(cate);
		return cateid;

	}
public   Object lastMap4dbg;
	private List<Map> list_cache(final String cate_id) {
		String cateIndexDir = pathx.classPathParent_jensyegeor()
				+ "/index_movs/cateIndexs";
		Closure indexGener = new Closure () {

			@Override
			public Object execute(Object arg0) throws Exception {
				IndexManager im=new IndexManager(pathx.classPathParent_jensyegeor()+"/index_movs");
				List<Map> li = getitemNameList_fullinfo();
				im.createIndex("cateIndexs","col", li, new Closure2 () {

					@Override
					public Object execute(Object arg0) {
						Map map=(Map) arg0;
						String f = (String) map.get("file_path");
						if(f==null || f.trim().length()==0)   //should use file as index ,,use thumb only for debug
							f= (String) map.get("thumb");
						// d:/z/爱情类/K歌情人/K歌情人.jpg==f
						lastMap4dbg=map;
						String cate_id = getCateid(f);
						if(cate_id==null)  //if file thumb all empty then empty
							System.out.println("dbg");
						return cate_id;
					}
				});
				return  null;
			}
		};
		Closure noIndexDataGener = new Closure () {

			@Override
			public Object execute(Object arg0) throws Exception {
			 
				List<Map> list_ori = list_ori(cate_id);
				Map m = new HashMap();
				m.put(cate_id, list_ori);

				return m;
			}
		};
		Map index = (Map) getDatas(cateIndexDir,indexGener,noIndexDataGener);
		
		return (List<Map>) index.get(cate_id);
	}

	private Object getDatas(String cateIndexDir, final Closure indexGener, Closure noIndexDataGener) {
		Object itemNameList = new ArrayList<Map>();
		final String index_file1 = cateIndexDir + "/1.txt";
		final String idx_f2 = cateIndexDir + "/2.txt";
		try {
			timeTester t=new timeTester(" rad index");
			itemNameList = SerialUtil.read(index_file1);
			t.printUseTime();
			filex.saveLog( String.valueOf("read index:"+ t.pasttime), "c:\\time");
			System.out.println(" use index :"+index_file1);
		} catch (Exception e) {
			try {

				itemNameList = SerialUtil.read(idx_f2);
				System.out.println(" use index2 :"+idx_f2);

			} catch (Exception e2) {
				try {// no index
					System.out.println(" no index return noIndexDataGener");
					timeTester t=new timeTester(" ca");
					itemNameList = noIndexDataGener.execute(null);
					t.printUseTime();
					filex.saveLog("noidex"+ String.valueOf(t.pasttime), "c:\\time");
					System.out.println("");
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				try {
					core.newThread(new Runnable() {
						
						@Override
						public void run() {
							Object index;
							try {
								System.out.println(" no index return  then gene index");
								index = indexGener.execute(null);
								new IndexStoreService().geneIndex(index,
										index_file1, idx_f2);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								filex.saveLog(e, "c:\\e");
							}

						}
					}, "threadName2");

				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					filex.saveLog(e1, "c:\\e");
				}
				
			}

		}
		return  itemNameList;
	}
	//public List<Map> list_ori_(String cate_id) 
	public List<Map> list_ori(String cate_id) {
		String cate_str = getCateCnnameDir(cate_id);
		
		System.out.println("----getCateCnnameDir:"+cate_str);

		List<String> subDirs = new ArrayList<String>();
		
		
		String dirname = maindir + cate_str;
		
		
		System.out.println("----mov partion dir path:"+dirname);

		try {

			subDirs = new dirx(dirname).subDirs();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			System.out.println("----mov partion dir datas:"+core.toJsonStrO88(subDirs));
		} catch (Throwable e) {
			// TODO: handle exception
		}
		
		List<String> mov_names = subDirs;
		List<Map> movs = new ArrayList<Map>();
		for (String mov_name : mov_names) {
			try {
				Map mv = new HashMap();
				String resDir = dirname + "/" + mov_name;
				mv.put("file_path", getFileName(resDir));
				mv.put("thumb", getPicName(resDir));
				mv.put("txt_file", getTxtName(resDir));
				mv.put("material_description", mov_name);
				mv.put("material_id", mv.get("file_path"));
				
				movs.add(mv);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return movs;
	}

	String cate_file;

	private String getCateCnnameDir(String cate) {
		String s = pathx.classPathParent_jensyegeor() + "/cate.txt";
		cate_file = s;
		Map m = YamlAtiX.getMap(s);
		return (String) m.get(cate);
	}

	private Object getPicName(String resDir) {
		String[] list = new File(resDir).list(new FilenameFilter() {

			@Override
			public boolean accept(File paramFile, String filename) {
				// path =----filename.ext
				String extname = filex.getExtName(filename);
				if ("jpg".contains(extname.toLowerCase()) || "jpeg".contains(extname.toLowerCase()))
					return true;
				else
					return false;
			}
		});
		try {// .substring(3)
			return resDir + "/" + list[0];
		} catch (Exception e) {
			return "";
		}
	}

	private Object getTxtName(String resDir) {
		String[] list = new File(resDir).list(new FilenameFilter() {

			@Override
			public boolean accept(File paramFile, String filename) {
				// path =----filename.ext
				String extname = filex.getExtName(filename);
				if ("txt".contains(extname.toLowerCase()))
					return true;
				else
					return false;
			}
		});
		try {
			return resDir.substring(3) + "/" + list[0];
		} catch (Exception e) {
			return "";
		}
	}

	public Object getFileName(String string) {
		//
		String mvExt = ".mkv  .avi 		 .m2ts		 .ts		 .iso		 .rmvb		 .mp4";
		final Set<String> st = strUtil.toSet(mvExt, strUtil.dotChar);
		String[] list = new File(string).list(new FilenameFilter() {

			@Override
			public boolean accept(File paramFile, String filename) {
				// path =----filename.ext
				String extname = filex.getExtName(filename);
				if (st.contains(extname.toLowerCase()))
					return true;
				else
					return false;
			}
		});
		try {
			int offsetStartIndex=maindir.length();
			
						return string.substring(offsetStartIndex) + "/" + list[0];
		} catch (Exception e) {
			return "";
		}

	}

	public Object detail() {
		return null;
	};

	public Object search(Object obj) {
		Map mx = new ParamX().urlParams2Map(obj.toString());
		String kw = (String) mx.get("param");
		List<Map> itemNameList = new ArrayList<Map>();

		String movListssSSeriialOBjFile = pathx.classPathParent_jensyegeor()
				+ "/index_movs/searchIndex";
		itemNameList = getDatas(movListssSSeriialOBjFile);

		List<Map> movs = new ArrayList<Map>();
		for (Map m : itemNameList) {

			try {
				String kws = PinyinX.getSimple((String) m
						.get("material_description"));
				if (kws.toLowerCase().contains(kw.toLowerCase()))
					movs.add(m);
			} catch (Throwable e) {
				e.printStackTrace();
			}

		}

		movs = getFullMovsInfo(movs);

		return core.toJsonStrO88(FormatterEasyuiImp.fmtList(movs));

		// return null;
	}


	public Object searchV2(Object obj) {
	//	Map mx = new ParamX().urlParams2Map(obj.toString());
		String kw = (String)obj;
		List<Map> itemNameList = new ArrayList<Map>();

		String movListssSSeriialOBjFile = pathx.classPathParent_jensyegeor()
				+ "/index_movs/searchIndex";
		itemNameList = getDatas(movListssSSeriialOBjFile);
		//[{file_path=z:/爱情类/初恋有病, material_description=初恋有病}
		List<Map> movs = new ArrayList<Map>();
		for (Map m : itemNameList) {
			System.out.println(m);
			try {
				String kws = PinyinX.getSimple((String) m
						.get("material_description"));
				if (kws.toLowerCase().contains(kw.toLowerCase()))
					movs.add(m);
			} catch (Throwable e) {
				e.printStackTrace();
			}

		}

	List 	movs2 = getFullMovsInfo(movs);
   System.out.println("");
		return AtiJson.toJson(FormatterEasyuiImp.fmtList(movs2));

		// return null;
	}

	/**
	 * for search only
	 * @param movListssSSeriialOBjFile
	 * @return
	 */
	private List<Map> getDatas(String movListssSSeriialOBjFile) {
		List<Map> itemNameList;
		String index_file1 = movListssSSeriialOBjFile + "/1.txt";
		String idx_f2 = movListssSSeriialOBjFile + "/2.txt";
		try {

			itemNameList = (List<Map>) SerialUtil.read(index_file1);
		} catch (Exception e) {
			try {

				itemNameList = (List<Map>) SerialUtil.read(idx_f2);

			} catch (Exception e2) {
				//{material_description=他其实没那么喜欢你, file_path=z:/爱情类/他其实没那么喜欢你}
				itemNameList = getitemNameList();
				new IndexStoreService().geneIndex(itemNameList, index_file1,
						idx_f2);
			}

		}
		return itemNameList;
	}

	// only for
	private List<Map> getFullMovsInfo(List<Map> movs) {
		for (int i = 0; i < movs.size(); i++) {
			Map m = movs.get(i);
			try {
				// Map mv = new HashMap();
				String resDir = (String) m.get("file_path");// getSingleItemMaindir();
//pah
				if(!resDir.contains(":"))
					resDir=getRecDir(resDir);
				 
				m.put("thumb", getPicName(resDir));
				m.put("txt_file", getTxtName(resDir));
				m.put("file_path", getFileName(resDir));
				m.put("material_id", m.get("file_path"));

			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return movs;
	}

	private String getRecDir(String resDir) {
		try {
			String[] a=resDir.split("/");
			String recDir = "z:/"+a[0]+"/"+a[1];
			return recDir;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return resDir;
	}


	private String getSingleItemMaindir(String f) {
		int last = f.lastIndexOf("/");
		return f.substring(0, last);
	}

	public List<Map> getitemNameList() {
		
		System.out.println("getitemNameList----------");
		final List<Map> li = new ArrayList<Map>();
		String mov_dirs = getMovieDirs();
		dirx.traveDirPa1(mov_dirs, new Closure<String, String>() {

			@Override
			public String execute(String f) throws Exception {
				if (f.contains("@Recycle") || f.contains("player"))
					return null;
				f = pathx.fixSlash(f);
				System.out.println(f);
				String[] a = f.split(strUtil.slashChar);

				if (a.length == getSuitlen()) {
					File f2 = new File(f);
					Map m = new HashMap();
					m.put("file_path", f);
					m.put("material_description", f2.getName());
					li.add(m);
				}
				return null;
			}
		});
		return li;
	}
	
 public List<Map> getitemNameList_fullinfo() {
		final List<Map> li = new ArrayList<Map>();
		String mov_dirs = getMovieDirs();
		dirx.traveDirPa1(mov_dirs, new Closure<String, String>() {

			@Override
			public String execute(String f) throws Exception {
				if (f.contains("@Recycle") || f.contains("player"))
					return null;
				f = pathx.fixSlash(f);
				System.out.println(f);
				String[] a = f.split(strUtil.slashChar);

				if (a.length == getSuitlen()) {
					File f2 = new File(f);
					Map m = new HashMap();
				//	m.put("file_path", f);
					m.put("material_description", f2.getName());
					
					
					String resDir =f; 

					m.put("thumb", getPicName(resDir));
					m.put("txt_file", getTxtName(resDir));
					m.put("file_path", getFileName(resDir));
					li.add(m);
				}
				return null;
			}
		});
		return li;
	}

	public int getSuitlen() {

		String[] a = maindir.split("/");

		return 3 + a.length - 1;
	}

	public int getOffsetlen() {

		String[] a = maindir.split("/");

		return a.length - 1;
	}

	private String getMovieDirs() {
		// TODO Auto-generated method stub
		getCateCnnameDir("0");
		maindir = pathx.fixSlash(maindir);
		List<Map> li = YamlAtiX.getList(cate_file);
		String r = "";
		for (Map map : li) {
			r = r + "," + maindir + map.get("lab");
		}
		return r;
	};

}
